/* 
 * This file part of cget - A libcurl based downloading tool.
 * http://lianwei3.googlepages.com/home2
 * Copyright (C) 2006 Wei Lian <lianwei3@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "header.h"

extern pthread_mutex_t lock;

size_t my_write_func(void *ptr, size_t size, size_t nmemb, void *stream)
{
    pthread_mutex_lock(&lock);
    struct BlockInfo *info = (struct BlockInfo *) stream;
    fseek(info->fp, info->seek, SEEK_SET);
    info->seek += fwrite(ptr, size, nmemb, info->fp);
    pthread_mutex_unlock(&lock);
    return size * nmemb;
}

int my_progress_func(void *stream, double t, double d, double ut,
		     double un)
{
    struct BlockInfo *info = (struct BlockInfo *) stream;
    int row, col;
    getmaxyx(stdscr, row, col);
    char str[col < 53 ? 53 : col];
    sprintf(str, "(%d) download=%10.f, totoal=%10.f, (%3.f %%)%s",
	    info->num, d, t, d * 100.0 / t,
	    info->url.substr(0, col - 52 > 0 ? col - 52 : 0).c_str());
    str[col - 1] = 0;
    mvprintw(info->num + 1, 1, str);
    refresh();
    return 0;
}

void *pull_one_url(void *stream)
{
    struct BlockInfo *info = (struct BlockInfo *) stream;

    CURL *curl = info->curl;
  NEXT:
    curl_easy_reset(curl);
    curl_easy_setopt(curl, CURLOPT_URL, info->url.c_str());
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_write_func);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, info);
    char range[64];
    sprintf(range, "%ld-%ld", info->seek, info->end);
    curl_easy_setopt(curl, CURLOPT_RANGE, range);
    curl_easy_setopt(curl, CURLOPT_NOPROGRESS, FALSE);
    curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, my_progress_func);
    curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, info);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
    curl_easy_perform(curl);
    ////////
    std::vector < BlockInfo > *vec_info = info->vecptr;
    long max = 100;
    int slowest_id = -1;
    long remain;
    ///find the slowest downloading thread
    for (uint i = 0; i < vec_info->size(); i++) {
	remain = vec_info->at(i).end - vec_info->at(i).seek;
	if (remain > max) {
	    max = remain;
	    slowest_id = i;
	}
    }
    assert(slowest_id != info->num);
    ///cancel the thread and let other finished thread do the job
    if (slowest_id != -1 && vec_info->at(slowest_id).flag == FALSE) {
	pthread_cancel(*(vec_info->at(slowest_id).thread));
	curl_easy_cleanup(vec_info->at(slowest_id).curl);
	vec_info->at(slowest_id).flag = TRUE;
	vec_info->at(slowest_id).url = info->url;
	vec_info->at(slowest_id).curl = info->curl;
	vec_info->at(slowest_id).thread = info->thread;
	info = &(vec_info->at(slowest_id));
	goto NEXT;
    }
    ///cleanup
    curl_easy_cleanup(curl);

    return NULL;
}

//-----------------------------------------------------------------------
size_t my_header_func(void *ptr, size_t size, size_t nmemb, void *stream)
{
    struct BlockInfo *info = (struct BlockInfo *) stream;
    char *str;
    if ((str = strstr((char *) ptr, "Content-Length:")))
	info->length = strtol(str + strlen("Content-Length:"), NULL, 0);
    return size * nmemb;
}

void *consistency_check(void *stream)
{
    struct BlockInfo *info = (struct BlockInfo *) stream;

    CURL *curl = info->curl;
    curl_easy_setopt(curl, CURLOPT_URL, info->url.c_str());
    curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, my_header_func);
    curl_easy_setopt(curl, CURLOPT_WRITEHEADER, info);
    curl_easy_setopt(curl, CURLOPT_NOBODY, TRUE);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
    curl_easy_perform(curl);

    return NULL;
}
